﻿using Microsoft.JSInterop;
using System.Text.Json;
using Volo.Abp.DependencyInjection;

namespace Tool.Services
{
    public class PythonService: IScopedDependency
    {
        private readonly IJSRuntime _jsRuntime;
        private readonly HttpClient _http;

        public PythonService(IJSRuntime jsRuntime, IHttpClientFactory httpClientFactory)
        {
            _jsRuntime = jsRuntime;
            _http = httpClientFactory.CreateClient("local");
        }

        public async Task<string> RunPythonCode(string code)
        {
            return await _jsRuntime.InvokeAsync<string>("MyLib.runPythonCode", code);
        }

        public async Task<string> ReadFileAsStringAsync(string path)
        {
            return await _http.GetStringAsync(path);
        }

        public async Task ImportLib(string path)
        {
            var script = await ReadFileAsStringAsync(path);
            await _jsRuntime.InvokeVoidAsync("MyLib.writeFileToPyodide", path, script);
        }

        public async Task<JsonElement> ProcessData()
        {
            // 读取 Python 脚本
            var script = await ReadFileAsStringAsync("data_processor.py");
            //await RunPythonCode(script);


            await _jsRuntime.InvokeVoidAsync("MyLib.writeFileToPyodide", "data_processor.py", script);

            // 读取 CSV 数据
            var csv = await ReadFileAsStringAsync("data.csv");

            // 调用 Python 函数
            var result = await _jsRuntime.InvokeAsync<string>("MyLib.runPythonCode", $@"
import sys
sys.path.append('/')
from data_processor import process_data
process_data('''{csv}''')
        ");

            var json = JsonDocument.Parse(result).RootElement;
            return json;
        }
    }
}
